
import 'package:sqflite/sqflite.dart';

import '../sqf_provider.dart';

///    author : leeo
///    e-mail : jkliao@yeah.net
///    date   : 2020-03-2910:48
///    desc   :
 class ProviderUser extends BaseDbProvider {
  final String tabName = "UserInfo";

  final String columnId = "_id";
  final String columnName = "userName";
  final String columnData = "data";

  String id;
  String name;
  String data;

  ProviderUser.fromMap(Map map) {
    id = map[columnId];
    name = map[columnName];
    data = map[data];
  }
  

  Map<String, dynamic> toMap(String userName, String data) {
    Map<String, dynamic> map = {columnName : userName, columnData : data};
    if (id != null) {
      map[columnId] = id;
    }
    return map;
  }

  @override
  tableName() => tabName;

  @override
  tableSqlString() => tableString(tabName, columnId) + '''
  $columnName TEXT NOT NULL,
  $columnData TEXT NOT NULL)
  ''';

  Future _getUserProvider(Database db, String userName) async {
    List<Map<String, dynamic>> res = await db.query(tabName, columns : [columnId, columnName, columnData], where: "$columnName=?", whereArgs: [userName]);
    if (res.length > 0) {
      ProviderUser providerUser = ProviderUser.fromMap(res.first);
      return providerUser;
    }
  }

  ///插入数据，判断是否已经有了，有了直接先删除然后插入
  Future insert(String userName, String data) async {
    Database database = await getDatabase();

    ProviderUser providerUser = await _getUserProvider(database, userName);
    if (null != providerUser) {
      await database.delete(tabName, where: "$columnName=?", whereArgs: [userName]);
    }
    return await database.insert(tabName, toMap(userName, data));
  }




 }